import * as fs from 'fs-extra';

const FsExtra = {
  async readFolder(path: string, includeSubdirectories = false, extensions:string[] = []): Promise<string[]> {
    try {
      let files = await fs.readdir(path, {withFileTypes: true});
      let result = files.reduce(async (accumulatorPromise, file) => {
        let accumulator = await accumulatorPromise;
        if (file.isDirectory()) {
          if (includeSubdirectories) {
            const subDirFiles = await FsExtra.readFolder(`${path}/${file.name}`, includeSubdirectories, extensions);
            accumulator = [...accumulator, ...subDirFiles];
          }
        } else {
          const ext = file.name.split('.').pop();
          if (extensions.length === 0 || extensions.includes(ext)) {
            accumulator.push(`${path}/${file.name}`);
          }
        }
        return accumulator;
      }, Promise.resolve([]));
      return result;
    } catch (err) {
      console.error(`Failed to read directory: ${err}`);
      return [];
    }
  },
  async readFileToArrayBuffer(filePath) {
    try {
      const buffer = await fs.readFile(filePath);
      const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
      return arrayBuffer;
    } catch (err) {
      console.error(`Failed to read file into ArrayBuffer: ${err}`);
      return null;
    }
  }
}

export default FsExtra
